<script lang="ts" setup>
import { apiGetPhoneCode } from "@/api/interface"
import { type LoginRequestData } from "@/api/interface/types/InterfaceTypes"
import { useUserStore } from "@/store/modules/user"
import { type FormInstance, type FormRules } from "element-plus"
import { reactive, ref } from "vue"
import { useRouter } from "vue-router"
// import ThemeSwitch from "@/components/ThemeSwitch/index.vue"
import LOGO from "@/assets/layouts/LOGO.svg"
import LeftLogo from "@/icons/svg/leftLogo.svg"
import Footer from "@/layouts/components/Footer/index.vue"
// import { setUserInfo } from '@/utils/cache/user'
import { useAppStore } from "@/store/modules/app"

const appStore = useAppStore()

const router = useRouter()
/** 登录表单元素的引用 */
const loginFormRef = ref<FormInstance | null>(null)

/** 登录按钮 Loading */
const loading = ref(false)

/** 登录表单数据 */
const loginFormData: LoginRequestData = reactive({
  mobile_numb: "",
  sms: "",
  rememberToLogIn: true
})

const rulesPhone = (rules: any, value: any, callback: any) => {
  if (!/^1[3456789]\d{9}$/.test(value)) {
    callback("手机号信息有误")
  } else {
    callback()
  }
}

/** 登录表单校验规则 */
const loginFormRules: FormRules = {
  mobile_numb: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "blur"
    },
    {
      validator: rulesPhone,
      trigger: "blur",
      message: "请输入正确手机号"
    }
  ],
  sms: [{ required: true, message: "请输入验证码", trigger: "blur" }]
}

/** 登录逻辑 */
const handleLogin = () => {
  loginFormRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      loading.value = true
      useUserStore()
        .login(loginFormData)
        .then(async (code) => {
          console.log(code, "登录成功")
          appStore.closeSidebar(false) //默认侧边栏关闭
          router.push({ path: "/" })
        })
        .catch(() => {
          console.log("登陆失败")
          loginFormData.sms = ""
        })
        .finally(() => {
          loading.value = false
        })
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}

const state = reactive({
  // 获取验证码
  getCodeText: "获取验证码",
  disabled: false,
  holdTime: 60 //默认60秒计时
})

const onGetCode = () => {
  try {
    const captchaId = "190901371"
    // 腾讯滑块验证码appid生成一个滑块验证码对象
    const captcha = new window.TencentCaptcha(captchaId, function (res: any) {
      if (res.ret === 0) {
        state.disabled = true
        state.getCodeText = "发送中..." //发送验证码
        setTimeout(() => {
          // showToast('验证码已发送')
          setTimer() //调用定时器方法
        }, 1000)
        codeMsg(res)
      }
    })
    // // 滑块显示
    captcha.show()
    // return
  } catch (error) {
    console.log(error)
  }
}

const codeMsg = (res: any) => {
  const p = {
    mobile_numb: loginFormData.mobile_numb,
    randstr: res.randstr,
    ticket: res.ticket
  }
  apiGetPhoneCode(p)
}
let Timer = null as any

function setTimer() {
  Timer = setInterval(() => {
    if (state.holdTime <= 0) {
      state.disabled = false
      state.getCodeText = "获取验证码"
      state.holdTime = 60
      clearInterval(Timer) //清除该函数
      return
    }
    state.getCodeText = `${state.holdTime}s后重新获取 `
    state.holdTime--
  }, 1000)
}
</script>

<template>
  <div class="login-container">
    <!-- <ThemeSwitch class="theme-switch" /> -->
    <el-row>
      <el-col :xs="24" :sm="10" class="isMedia">
        <div class="leftLogo">
          <div>
            <div class="logoTxt">
              <img :src="LOGO" alt="" srcset="" />
              <div class="span">YUNSHAN TEC</div>
            </div>
            <img :src="LeftLogo" alt="" srcset="" />
            <Footer />
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="14">
        <div class="login-card">
          <transition name="el-fade-in">
            <div class="login-right">
              <div class="title">
                <!-- <img src="@/assets/layouts/logo-text-2.png" /> -->
                登录云珊AI中台
              </div>
              <div class="content">
                <el-form
                  :label-position="'top'"
                  label-width="100px"
                  ref="loginFormRef"
                  :model="loginFormData"
                  :rules="loginFormRules"
                  @keyup.enter="handleLogin"
                >
                  <el-form-item label="手机号" prop="mobile_numb">
                    <el-input
                      v-model.trim="loginFormData.mobile_numb"
                      maxlength="11"
                      placeholder="请输入手机号"
                      size="large"
                    />
                  </el-form-item>

                  <el-form-item label="短信验证码" prop="sms">
                    <el-input
                      v-model.trim="loginFormData.sms"
                      placeholder="请输入短信验证码"
                      maxlength="6"
                      size="large"
                    >
                      <template #append>
                        <button :disabled="state.disabled" @click.prevent="onGetCode" class="getCode">
                          {{ state.getCodeText }}
                        </button>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-button
                    color="#333"
                    type="primary"
                    class="smBt"
                    :loading="loading"
                    size="large"
                    @click.prevent="handleLogin"
                    >登录</el-button
                  >
                  <el-checkbox v-model="loginFormData.rememberToLogIn" label="记住登录信息" size="large" />
                </el-form>
              </div>
            </div>
          </transition>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.login-container {
  // align-items: center;
  min-height: 100%;
  background: #fff;

  ::v-deep .el-form--default.el-form--label-top .el-form-item .el-form-item__label {
    color: #333333;
    font-size: 14px;
    font-weight: 500;
  }

  ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #333333;
    border-color: #333333;
  }

  ::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #606266;
  }

  .getCode {
    margin: 0 10px;
    cursor: pointer;
    color: #333333;
    border: none;
    background: #fff;
  }

  ::v-deep .el-input-group__append {
    background: #fff;
  }

  .theme-switch {
    position: fixed;
    top: 5%;
    right: 5%;
    cursor: pointer;
  }

  .leftLogo {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    text-align: center;
    background-image: url("../../assets/layouts/Maskgroup.png");
    background-size: 100% 100%;

    .logoTxt {
      // line-height: 40px;
      display: flex;
      margin-bottom: 50px;
      justify-content: center;
      align-items: center;

      .span {
        font-size: 24px;
        font-weight: 600;
        margin-left: 10px;
      }
    }
  }

  .login-card {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;

    .login-right {
      min-width: 40%;
    }

    .title {
      display: flex;
      // justify-content: center;
      // align-items: center;
      font-weight: 600;
      letter-spacing: 0px;
      text-align: left;
      color: #333333;
      margin-bottom: 50px;
      font-size: 28px;

      img {
        height: 100%;
      }
    }

    .content {
      // padding: 20px 50px 50px 50px;
      :deep(.el-input-group__append) {
        padding: 0;
        overflow: hidden;

        .el-image {
          width: 100px;
          height: 40px;
          border-left: 0px;
          user-select: none;
          cursor: pointer;
          text-align: center;
        }
      }

      .el-button {
        width: 100%;
        margin-top: 40px;
      }

      .el-button:focus,
      .el-button:hover {
        border-color: #333;
        background-color: #333;
        outline: 0;
      }
    }
  }
}
</style>
